package com.luoxiang.socialandroid.utils;

import android.text.TextUtils;
import android.util.Log;

import com.luoxiang.lib_common.common.Config;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author 梁馨
 * @description:
 * @date :2022/3/9 9:33
 */
public class NetUtils2 {

    private ApiService apiService;

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private String nonce;

    private String currtime;

    private String checksum;

    public NetUtils2() {
        initModel();
    }

    private static class Callack {
        private static final NetUtils2 NET_UTILS = new NetUtils2();
    }

    public static NetUtils2 getInstance() {
        return Callack.NET_UTILS;
    }

    private void initModel() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient build = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addNetworkInterceptor(httpLoggingInterceptor)
                .addInterceptor(new Heades())
                .addInterceptor(new ResponseDecryptLogInterceptor())
                .build();
        Retrofit build1 = new Retrofit.Builder()
//                .baseUrl("http://192.168.0.120:8888/")
                .baseUrl(Config.BaseUrl)
                .client(build)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiService = build1.create(ApiService.class);
    }

    public ApiService getApiService() {
        return apiService;
    }

    private class Heades implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            getRequest();
            Request request = chain.request();
            if (TextUtils.isEmpty(nonce) || TextUtils.isEmpty(currtime) || TextUtils.isEmpty(checksum)) {
                return chain.proceed(request);
            }
            Log.d("getRequest", "nonce ->" + nonce + "currTime -> " + currtime + "checkSum -> " + checksum);
            Request head1 = request.newBuilder()
                    .addHeader("nonce", nonce)
                    .addHeader("currTime", currtime)
                    .addHeader("checkSum", checksum)
                    .build();
            return chain.proceed(head1);
        }
    }

    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        this.nonce = nonce;
        this.currtime = currTime;
        this.checksum = newCheckSum;
    }
}
